﻿using CommunityToolkit.Mvvm.Input;
using HslCommunication.Profinet.Siemens;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Common;
using ZoneLineNew.Core;
using ZoneLineNew.Enums;
using ZoneLineNew.Models;
using ZoneLineNew.Models.Dto;
using ZoneLineNew.Models.Entity;
using ZoneLineNew.Models.Entity.BaseInfo;
using ZoneLineNew.Models.StationConfig;
using ZoneLineNew.Models.StationResult.HOPStation;
using ZoneLineNew.Models.StationResult.QOPStation;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;
using ZoneLineNew.Services.Station;
using ZoneLineNew.ViewModelBase;

namespace ZoneLineNew.ViewModels.Dialogs {

    public class SelectProductDialogViewModel : DialogViewModel {

        private readonly IWorkStationService<QOP010StationResult, QOP010StationConfig> _workStationQOP010Service;
        private readonly IWorkStationService<QOP050LStationResult, QOP050LStationConfig> _workStationQOP050LService;
        private readonly IWorkStationService<QOP050RStationResult, QOP050RStationConfig> _workStationQOP050RService;
        private readonly IWorkStationService<HOP010StationResult, HOP010StationConfig> _workStationHOP010Service;
        private readonly IWorkStationService<HOP040StationResult, HOP040StationConfig> _workStationHOP040Service;

        private readonly IDbOperate<IFreeSqlMainContext> _mainDbOperate = null;
        public SelectProductDialogViewModel(
            IRegionManager regionManager,
            IDialogService dialog, 
            IEventAggregator eventAggregator, 
            IMessageService message, 
            IDbOperate<IFreeSqlMainContext> mainDbOperate,
            IWorkStationService<QOP010StationResult, QOP010StationConfig> workStationQOP010Service,
            IWorkStationService<QOP050LStationResult, QOP050LStationConfig> workStationQOP050LService,
            IWorkStationService<QOP050RStationResult, QOP050RStationConfig> workStationQOP050RService,
            IWorkStationService<HOP010StationResult, HOP010StationConfig> workStationHOP010Service,
            IWorkStationService<HOP040StationResult, HOP040StationConfig> workStationHOP040Service
            ) 
            : base(regionManager, dialog, eventAggregator, message, mainDbOperate) {

            this._mainDbOperate = mainDbOperate;
            this._workStationQOP010Service = workStationQOP010Service; 
            this._workStationQOP050LService = workStationQOP050LService;
            this._workStationQOP050RService = workStationQOP050RService;
            this._workStationHOP010Service = workStationHOP010Service;
            this._workStationHOP040Service = workStationHOP040Service;

            GetStationList();

            //加载启用站
            var config = base._mainDbOperate.GetModel<StationEnableConfig>(p => true);
            if (Cache.IsQopStaion) {
                //前减下叉臂装配-550
                ComboxItemDto station = StationEnabeleds.First(o => o.Index == 2);
                station.Content = config.OP006StationEnable == 1;
                //前减垫片机-560
                station = StationEnabeleds.First(o => o.Index == 3);
                station.Content = config.OP020StationEnable == 1;
                //前减弹簧测高-570
                station = StationEnabeleds.First(o => o.Index == 4);
                station.Content = config.OP010StationEnable == 1;
                //前减上支撑螺母拧紧-580-1
                station = StationEnabeleds.First(o => o.Index == 5);
                station.Content = config.OP050LStationEnable == 1;
                //前减上支撑螺母拧紧-5802
                station = StationEnabeleds.First(o => o.Index == 6);
                station.Content = config.OP050RStationEnable == 1;
            } else if (Cache.IsHopStaion) {
                //后减衬套压装-620
                ComboxItemDto station = StationEnabeleds.First(o => o.Index == 0);
                station.Content = config.HOP010StationEnable == 1;
                //后减上支撑螺母拧紧-640
                station = StationEnabeleds.First(o => o.Index == 1);
                station.Content = config.HOP040StationEnable == 1;
            }

            //加载客户列表
            var clist = base._mainDbOperate.GetModelList<CustomerEntity>(o => true);
            CustomerTypes.Clear();
            CustomerTypes.AddRange(clist);
        }

        #region Props
        private ObservableCollection<ComboxItemDto> _stationEnabeleds = new ObservableCollection<ComboxItemDto>();
        /// <summary>
        /// 工位启用列表
        /// </summary>
        public ObservableCollection<ComboxItemDto> StationEnabeleds {
            get { return _stationEnabeleds; }
            set { _stationEnabeleds = value; RaisePropertyChanged(); }
        }


        private ObservableCollection<CustomerEntity> customerTypes = new ObservableCollection<CustomerEntity>();
        /// <summary>
        /// 客户列表
        /// </summary>
        public ObservableCollection<CustomerEntity> CustomerTypes {
            get { return customerTypes; }
            set { customerTypes = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<ProductDto> productionTypes = new ObservableCollection<ProductDto>();
        /// <summary>
        /// 产品列表
        /// </summary>
        public ObservableCollection<ProductDto> ProductionTypes {
            get { return productionTypes; }
            set { productionTypes = value; RaisePropertyChanged(); }
        }


        private ObservableCollection<KeyValuePair<string,string>> _productionRecipes = new ObservableCollection<KeyValuePair<string, string>>();
        /// <summary>
        /// 产品配方
        /// </summary>
        public ObservableCollection<KeyValuePair<string,string>> ProductionRecipes {
            get { return _productionRecipes; }
            set { _productionRecipes = value; RaisePropertyChanged(); }
        }
        #endregion


        #region Commands

        public DelegateCommand<CustomerEntity> CustomerTypeSelectedCmd => new DelegateCommand<CustomerEntity>((rhs) => {

            if (rhs != null) {
                var plist = _mainDbOperate.GetFreeSql().Select<ProductEntity, CustomerEntity>()
                 .LeftJoin((a, b) => a.CustomerID == b.Id)
                 .Where((a, b) => a.CustomerID == rhs.Id)
                 .ToList((a, b) => new ProductDto {
                     ProductName = a.ProductName,
                     Description = a.Description,
                     Id = a.Id,
                     Model = a.Model,
                     Memo = a.Memo,
                     WorkDirection = a.WorkDirection,
                     MaterialNumber = a.MaterialNumber,
                     Unit = a.Unit,
                     CustomerID = b.Id,
                     CustomerName = b.Name,
                 });
                ProductionTypes.Clear();
                ProductionTypes.AddRange(plist);
                Cache.CurWorkProduct = null;
                Cache.CurrentFormula.Clear();
                ProductionRecipes.Clear();
            }
        });

        public DelegateCommand<ProductDto> ProductionTypeSelectedCmd => new DelegateCommand<ProductDto>((rhs) => {
            if (rhs == null) {
                return;
            }
            Cache.CurWorkProduct = rhs;
            Cache.CurrentFormula.Clear();
            ProductionRecipes.Clear();
            var pecipeList = _mainDbOperate.GetModelList<RecipeEntity>(o => o.ProductID == rhs.Id);//获取配方列表
            foreach (var item in pecipeList) {
                ProductionRecipes.Add(new KeyValuePair<string, string>(item.StationCode, item.RecipeNumber));
            }
        });

        public DelegateCommand<ProductDto> LoadRecipeCommand => new DelegateCommand<ProductDto>((rhs) => {

            if (rhs == null) {
                _message.Warning("请选择生产产品！");
                return;
            }

            var mbox = _message.Ask("确定所有设备均为【手动模式】，并且载入当前所选择的【产品配方】吗？");
            if (mbox != System.Windows.MessageBoxResult.OK) {
                return;
            }

            var pecipeList = _mainDbOperate.GetModelList<RecipeEntity>(o => o.ProductID == rhs.Id);//获取配方列表
            if (pecipeList == null || pecipeList.Count == 0) {
                _message.Error("当前产品配方未定义！");
                return;
            }

            foreach (var item in pecipeList) {

                SiemensS7Net siemensS7Net = default;
                FormulaDBConfigModel formulaDBConfig = default;

                if (item.StationCode == _workStationQOP010Service.StationConfig.StationCode) {//570

                    siemensS7Net = _workStationQOP010Service.GetSiemensS7Client();
                    formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == _workStationQOP010Service.StationConfig.Ip);

                } else if (item.StationCode == _workStationQOP050LService.StationConfig.StationCode) {//580-1

                    siemensS7Net = _workStationQOP050LService.GetSiemensS7Client();
                    formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == _workStationQOP050LService.StationConfig.Ip);

                } else if (item.StationCode == _workStationQOP050RService.StationConfig.StationCode) {//580-2

                    siemensS7Net = _workStationQOP050RService.GetSiemensS7Client();
                    formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == _workStationQOP050RService.StationConfig.Ip);

                } else if (item.StationCode == _workStationHOP010Service.StationConfig.StationCode) {//620

                    siemensS7Net = _workStationHOP010Service.GetSiemensS7Client();
                    formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == _workStationHOP010Service.StationConfig.Ip);

                } else if (item.StationCode == _workStationHOP040Service.StationConfig.StationCode) {//640

                    siemensS7Net = _workStationHOP040Service.GetSiemensS7Client();
                    formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == _workStationHOP040Service.StationConfig.Ip);

                }

                if (siemensS7Net != null && formulaDBConfig != null) {

                    var downVal = Convert.ToInt16(item.RecipeNumber);
                    var res = siemensS7Net.Write(formulaDBConfig.FormuladNumberAddr, downVal);
                    if (res.IsSuccess) {
                        siemensS7Net.Write(formulaDBConfig.FormuladDownloadAddr, true);
                        System.Threading.Thread.Sleep(200);
                        siemensS7Net.Write(formulaDBConfig.FormuladDownloadAddr, false);
                        var readVal = siemensS7Net.ReadInt16(formulaDBConfig.FormuladPLCUseAddr)?.Content;
                        if (downVal != readVal) {
                            _message.Error($"{item.StationCode}载入配方失败，载入后的配方号与读取的不一致！");
                            return;
                        }
                    } else {
                        _message.Error($"载入配方失败！{res.Message}");
                        return;
                    }

                }

                Cache.CurrentFormula.Add(new FormulaItem {
                    StationCode = item.StationCode,
                    IP = formulaDBConfig.PlcIp,
                    FormulaNumber = Convert.ToInt16(item.RecipeNumber),
                    ProductDto = JsonConvert.DeserializeObject<ProductDto>(JsonConvert.SerializeObject(rhs))
                });

            }
            _message.GrowSuccess("载入配方成功，请点击【开始】按钮进入生产！");
        });

        public DelegateCommand StartCommand => new DelegateCommand(() => {
            bool saveRlt = false;

            if (Cache.CurWorkProduct == null) {
                _message.Warning("请选择生产产品！");
                return;
            }

#if !DEBUG   
            if (Cache.IsQopStaion && Cache.CurrentFormula.Count != 3) {
                _message.Warning("请载入产品配方！");
                return;
            }else if (Cache.IsHopStaion && Cache.CurrentFormula.Count != 2) {
                _message.Warning("请载入产品配方！");
                return;
            }
#endif

            #region 保存选择状态
            var stationEnableConfig = new StationEnableConfig();
            if (Cache.IsQopStaion) {
                //前减下叉臂装配-550
                ComboxItemDto station = StationEnabeleds.First(o => o.Index == 2);
                stationEnableConfig.OP006StationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                //前减垫片机-560
                station = StationEnabeleds.First(o => o.Index == 3);
                stationEnableConfig.OP020StationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                //前减弹簧测高-570
                station = StationEnabeleds.First(o => o.Index == 4);
                stationEnableConfig.OP010StationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                //前减上支撑螺母拧紧-580-1
                station = StationEnabeleds.First(o => o.Index == 5);
                stationEnableConfig.OP050LStationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                //前减上支撑螺母拧紧-5802
                station = StationEnabeleds.First(o => o.Index == 6);
                stationEnableConfig.OP050RStationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                saveRlt = base._mainDbOperate.UpdateModel<StationEnableConfig>(p => true, s => new StationEnableConfig() {
                    OP006StationEnable = stationEnableConfig.OP006StationEnable,
                    OP010StationEnable = stationEnableConfig.OP010StationEnable,
                    OP020StationEnable = stationEnableConfig.OP020StationEnable,
                    OP050LStationEnable = stationEnableConfig.OP050LStationEnable,
                    OP050RStationEnable = stationEnableConfig.OP050RStationEnable,
                });

                //序列号同步(前减旧=>新)
                ProductIndexHelper.SynchronizeToNewSystemIndex(Cache.CurWorkProduct, ePrintStartionCode.Q_OP580_1);
                ProductIndexHelper.SynchronizeToNewSystemIndex(Cache.CurWorkProduct, ePrintStartionCode.Q_OP580_2);

            } else if (Cache.IsHopStaion) {
                //后减衬套压装-620
                ComboxItemDto station = StationEnabeleds.First(o => o.Index == 0);
                stationEnableConfig.HOP010StationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                //后减上支撑螺母拧紧-640
                station = StationEnabeleds.First(o => o.Index == 1);
                stationEnableConfig.HOP040StationEnable = (bool)station.Content ? 1 : 0;
                if ((bool)station.Content) {
                    Cache.WorkStationValidationList.Add(station.Key);
                }

                saveRlt = base._mainDbOperate.UpdateModel<StationEnableConfig>(p => true, s => new StationEnableConfig() {
                    HOP010StationEnable = stationEnableConfig.HOP010StationEnable,
                    HOP040StationEnable = stationEnableConfig.HOP040StationEnable,
                });


                //序列号同步(后减旧=>新)
                ProductIndexHelper.SynchronizeToNewSystemIndex(Cache.CurWorkProduct, ePrintStartionCode.H_OP640);
            }
            #endregion

            //验证通过
            base.OnDialogClosed(ButtonResult.OK);
        });
        #endregion



        #region 配方功能

        private ObservableCollection<StationConfigBase> stationConfigList;
        /// <summary>
        /// 配方下载工站列表
        /// </summary>
        public ObservableCollection<StationConfigBase> StationConfigList {
            get { return stationConfigList; }
            set { stationConfigList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<FormulaConfigModel> formulaConfigModelList;
        /// <summary>
        /// 配方详情
        /// </summary>
        public ObservableCollection<FormulaConfigModel> FormulaConfigModelList {
            get { return formulaConfigModelList; }
            set { formulaConfigModelList = value; RaisePropertyChanged(); }
        }

        private int? _currentPLCUseFormulaNumber;
        /// <summary>
        /// 当前PLC使用配方
        /// </summary>
        public int? CurrentPLCUseFormulaNumber {
            get { return _currentPLCUseFormulaNumber; }
            set { _currentPLCUseFormulaNumber = value; RaisePropertyChanged(); }
        }

        private int? _currentViewFormulaNumber;
        /// <summary>
        /// 当前查看配方
        /// </summary>
        public int? CurrentViewFormulaNumber {
            get { return _currentViewFormulaNumber; }
            set { _currentViewFormulaNumber = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<int?> _formulaNumberList;
        /// <summary>
        /// 配方序号列表
        /// </summary>
        public ObservableCollection<int?> FormulaNumberList {
            get { return _formulaNumberList; }
            set { _formulaNumberList = value; RaisePropertyChanged(); }
        }

        private FormulaDBConfigModel _formulaDBConfigModel;
        /// <summary>
        /// 配方数据点位
        /// </summary>
        public FormulaDBConfigModel FormulaDBConfigModel {
            get { return _formulaDBConfigModel; }
            set { _formulaDBConfigModel = value; RaisePropertyChanged(); }
        }


        private string _ip;
        private string _remark;
        private string _stationCode;

        public RelayCommand<StationConfigBase> StationConfigSelectedCmd => new RelayCommand<StationConfigBase>((obj) => {
            if (obj != null) {
                _ip = obj.Ip;
                _remark = obj.Remark;
                _stationCode = obj.StationCode;
                GetFormulaWriteDBAddrList(_ip);//获取当前工位配方点位信息
                GetCurrentStationUseFormula(_ip);//获取当前工位使用的配方
                GetFormulaConfigModelList(_ip, CurrentPLCUseFormulaNumber);//获取配方数据项
            }
        });

        public RelayCommand ReduceCmd => new RelayCommand(() => {
            if (CurrentViewFormulaNumber <= 1) {
                return;
            } else {
                CurrentViewFormulaNumber--;
                GetFormulaConfigModelList(_ip, CurrentViewFormulaNumber);
            }
        });

        public RelayCommand AddCmd => new RelayCommand(() => {
            if (CurrentViewFormulaNumber >= FormulaNumberList.Count) {
                return;
            } else {
                CurrentViewFormulaNumber++;
                GetFormulaConfigModelList(_ip, CurrentViewFormulaNumber);
            }
        });

        public RelayCommand DownloadCmd => new RelayCommand(() => {
            var mbox = HandyControl.Controls.MessageBox.Ask("确定当前设备为手动模式，并且下载当前选择的配方数据吗？", "温馨提示");
            if (mbox == System.Windows.MessageBoxResult.OK) {
                Task.Run(async () => {
                    bool res = false;
                    res = WriteData(FormulaDBConfigModel.FormuladNumberAddr, CurrentViewFormulaNumber.Value);
                    await Task.Delay(500);
                    WriteData(FormulaDBConfigModel.FormuladDownloadAddr, true);
                    await Task.Delay(500);
                    WriteData(FormulaDBConfigModel.FormuladDownloadAddr, false);
                    if (res) {
                        GetCurrentStationUseFormula(_ip);//重新获取一次PLC配方
                        if (CurrentPLCUseFormulaNumber != CurrentViewFormulaNumber.Value) {
                            HandyControl.Controls.MessageBox.Error("下载配方失败，读取不一致，请检查设备是否为在线模式！", "温馨提示");
                            return;
                        }
                        //缓存起来，如存在则先移除在新增
                        if (Cache.CurrentFormula.Where(o => o.IP == _ip).Count() > 0) {
                            Cache.CurrentFormula.Remove(Cache.CurrentFormula.Where(o => o.IP == _ip).FirstOrDefault());
                        }
                        FormulaItem formulaItem = new FormulaItem();
                        formulaItem.IP = _ip;
                        formulaItem.StationCode = _stationCode;
                        formulaItem.Remark = _remark;
                        formulaItem.FormulaNumber = CurrentPLCUseFormulaNumber.Value;
                        formulaItem.Model = ModelEnum.LX;


                        if (_ip == "192.168.10.10" || _ip == "192.168.10.25") //后减
                        {
                            var productType = FormulaConfigModelList.Where(o => o.FieldDescription == "配方名")?.FirstOrDefault().FieldValue;
                            if (productType != null && productType != "") {
                                formulaItem.CurrentProductType = productType;
                            }

                            var leftRight = FormulaConfigModelList.Where(o => o.FieldDescription == "产品型号").FirstOrDefault().FieldValue.ToUpper();
                            if (leftRight == "L") {
                                formulaItem.WorkDirection = WorkDirectionEnum.Left;
                            } else if (leftRight == "R") {
                                formulaItem.WorkDirection = WorkDirectionEnum.Right;
                            } else {
                                formulaItem.WorkDirection = WorkDirectionEnum.None;
                            }
                        } else if (_ip == "192.168.10.75" || _ip == "192.168.10.90" || _ip == "192.168.10.105")//前减-弹簧测高 前减-上支撑螺母拧紧工位(左) | 前减-上支撑螺母拧紧工位(右)
                          {
                            //工作左右件选择 X04(0是左件，1是右件) W04(1是左件，0是右件)
                            var productType = FormulaConfigModelList.Where(o => o.FieldDescription == "产品型号")?.FirstOrDefault().FieldValue;
                            if (productType != null && productType != "") {
                                formulaItem.CurrentProductType = productType;
                            }

                            var formulaName = FormulaConfigModelList.Where(o => o.FieldDescription.Contains("工作左右件选择"))?.FirstOrDefault().FieldValue;
                            if (formulaName != null && formulaName != "") {
                                if (productType == "W04" && formulaName == "1") {
                                    formulaItem.WorkDirection = WorkDirectionEnum.Left;
                                } else if (productType == "W04" && formulaName == "0") {
                                    formulaItem.WorkDirection = WorkDirectionEnum.Right;
                                } else if (productType == "X04" && formulaName == "0") {
                                    formulaItem.WorkDirection = WorkDirectionEnum.Left;
                                } else if (productType == "X04" && formulaName == "1") {
                                    formulaItem.WorkDirection = WorkDirectionEnum.Right;
                                }
                            }
                        }
                        Cache.CurrentFormula.Add(formulaItem);
                        HandyControl.Controls.MessageBox.Success("下载配方成功！", "温馨提示");
                    } else {
                        HandyControl.Controls.MessageBox.Success("下载配方失败！", "温馨提示");
                    }
                });
            }
        });


        /// <summary>
        /// 获取工站列表
        /// </summary>
        private void GetStationList() {

            StationConfigList = new ObservableCollection<StationConfigBase>();
            StationEnabeleds = new ObservableCollection<ComboxItemDto>();

            if (Cache.IsQopStaion) {

                var obj3 = _mainDbOperate.GetModelList<QOP006StationConfig>(o => 1 == 1).FirstOrDefault();
                var obj4 = _mainDbOperate.GetModelList<QOP020StationConfig>(o => 1 == 1).FirstOrDefault();
                var obj5 = _mainDbOperate.GetModelList<QOP010StationConfig>(o => 1 == 1).FirstOrDefault();
                var obj6 = _mainDbOperate.GetModelList<QOP050LStationConfig>(o => 1 == 1).FirstOrDefault();
                var obj7 = _mainDbOperate.GetModelList<QOP050RStationConfig>(o => 1 == 1).FirstOrDefault();
                //StationConfigList.Add(obj3);
                //StationConfigList.Add(obj5);
                StationConfigList.Add(obj5);
                StationConfigList.Add(obj6);
                StationConfigList.Add(obj7);

                StationEnabeleds.Add(new ComboxItemDto { Descr = obj3.Remark, Key = obj3.StationCode, Remark = obj3.Remark, Content = false, Index = 2 });
                StationEnabeleds.Add(new ComboxItemDto { Descr = obj4.Remark, Key = obj4.StationCode, Remark = obj4.Remark, Content = false, Index = 3 });
                StationEnabeleds.Add(new ComboxItemDto { Descr = obj5.Remark, Key = obj5.StationCode, Remark = obj5.Remark, Content = false, Index = 4 });
                StationEnabeleds.Add(new ComboxItemDto { Descr = obj6.Remark, Key = obj6.StationCode, Remark = obj6.Remark, Content = false, Index = 5 });
                StationEnabeleds.Add(new ComboxItemDto { Descr = obj7.Remark, Key = obj7.StationCode, Remark = obj7.Remark, Content = false, Index = 6 });

            } else if (Cache.IsHopStaion) {

                var obj1 = _mainDbOperate.GetModelList<HOP010StationConfig>(o => 1 == 1).FirstOrDefault();
                var obj2 = _mainDbOperate.GetModelList<HOP040StationConfig>(o => 1 == 1).FirstOrDefault();

                StationConfigList.Add(obj1);
                StationConfigList.Add(obj2);

                StationEnabeleds.Add(new ComboxItemDto { Descr = obj1.Remark, Key = obj1.StationCode, Remark = obj1.Remark, Content = false, Index = 0 });
                StationEnabeleds.Add(new ComboxItemDto { Descr = obj2.Remark, Key = obj2.StationCode, Remark = obj2.Remark, Content = false, Index = 1 });
            }

            //配方设备选择列表
            foreach (var item in StationConfigList) {
                item.Remark = $"{item.StationCode}{item.Remark}";
            }
        }


        /// <summary>
        /// 获取工作配置信息
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="formulaNumber"></param>
        private void GetFormulaConfigModelList(string ip = "", int? formulaNumber = null) {
            var list = new List<FormulaConfigModel>();
            if (ip != "") {
                list = _mainDbOperate.GetModelList<FormulaConfigModel>(o => o.PlcIp == ip);
            } else {
                list = _mainDbOperate.GetModelList<FormulaConfigModel>(o => true);
            }

            if (list.Count > 0) {
                FormulaNumberList = new ObservableCollection<int?>(list.Select(o => o.Number).Distinct().ToList());
                if (formulaNumber.HasValue) {
                    CurrentViewFormulaNumber = formulaNumber;
                    FormulaConfigModelList = new ObservableCollection<FormulaConfigModel>(list.Where(o => o.Number == formulaNumber).ToList());
                } else {
                    CurrentViewFormulaNumber = FormulaNumberList.FirstOrDefault().Value;
                    FormulaConfigModelList = new ObservableCollection<FormulaConfigModel>(list.Where(o => o.Number == CurrentViewFormulaNumber).ToList());
                }
            } else {
                FormulaNumberList = default;
                CurrentViewFormulaNumber = default;
                FormulaConfigModelList = default;
            }
        }

        /// <summary>
        /// 获取当前工站使用的配方号
        /// </summary>
        private void GetCurrentStationUseFormula(string ip) {
            try {
                SiemensS7Net _client = new SiemensS7Net(SiemensPLCS.S1200);
                _client.IpAddress = ip;
                _client.SetPersistentConnection();
                _client.Port = 102;
                var readContent = _client.ReadInt16(FormulaDBConfigModel.FormuladPLCUseAddr)?.Content;
                if (readContent != null) {
                    var readRlt = Convert.ToInt32(readContent);//读取当前配方地址
                    CurrentPLCUseFormulaNumber = readRlt;
                } else {
                    HandyControl.Controls.MessageBox.Error("获取PLC配方失败！", "温馨提示");
                }
                _client.ConnectClose();
            } catch (Exception ex) {
                HandyControl.Controls.MessageBox.Error(ex.Message, "温馨提示");
            }
        }

        /// <summary>
        /// 获取工作配方数据点位
        /// </summary>
        /// <param name="ip"></param>
        private void GetFormulaWriteDBAddrList(string ip) {
            var formulaDBConfig = _mainDbOperate.GetModel<FormulaDBConfigModel>(o => o.PlcIp == ip);
            FormulaDBConfigModel = formulaDBConfig;
        }

        private bool WriteData(string address, bool data) {
            bool res = false;
            try {
                SiemensS7Net _client = new SiemensS7Net(SiemensPLCS.S1200);
                _client.IpAddress = _ip;
                _client.SetPersistentConnection();
                _client.Port = 102;
                LogManager.Debug($"配方板块,上位机下发{address}点位数据,参数:{data}");
                var rls = _client.Write(address, data);
                LogManager.Debug($"配方板块,上位机下发{address}点位数据,结果:{rls.IsSuccess}");
                _client.ConnectClose();
                res = rls.IsSuccess;
            } catch (Exception ex) {
                HandyControl.Controls.MessageBox.Error(ex.Message);
            }
            return res;
        }

        private bool WriteData(string address, int data) {
            bool res = false;
            try {
                SiemensS7Net _client = new SiemensS7Net(SiemensPLCS.S1200);
                _client.IpAddress = _ip;
                _client.SetPersistentConnection();
                _client.Port = 102;
                LogManager.Info($"配方板块，上位机下发{address}点位数据，参数:{data}");
                var rls = _client.Write(address, (short)data);
                LogManager.Info($"配方板块，上位机下发{address}点位数据，参数:{data}，结果:{rls.IsSuccess}");
                _client.ConnectClose();
                res = rls.IsSuccess;
                var readValue = _client.ReadInt16(address).Content;
                LogManager.Info($"配方板块，从下位机读取{address}点位数据，结果:{readValue}");
            } catch (Exception ex) {
                HandyControl.Controls.MessageBox.Error(ex.Message, "温馨提示");
                //throw;
            }
            return res;
        }
        #endregion

    }


}
